package com.xz.knowledgeDuplication.thread.advice;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 锁 可重入锁
 * @author 召
 * @date 2022-07-26 21:31:38
 */
public class Lock implements Runnable {

    private int tickerNumber = 10;

    /**
     * 定义lock锁 显示的锁需要手动开关
     */
    private final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Lock lock = new Lock();
        new Thread(lock).start();
        new Thread(lock).start();
        new Thread(lock).start();
    }

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (tickerNumber > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(tickerNumber--);
                } else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
